<template>
  <div class="home">
    <!-- 顶部搜索栏 -->
    <div class="search-bar">
      <div class="search-input">
        <van-icon class="search-icon" name="search" />
        <input
          v-model="searchText"
          class="input-field"
          placeholder="飞机票查询，机票预订，机票"
          type="text"
        />
      </div>
      <van-icon class="user-icon" name="user-o" @click="handleUserClick" />
    </div>

    <!-- 主要内容区 -->
    <div class="main-content">
      <!-- 改回使用背景图片 -->
      <div class="bg-image"></div>

      <!-- 机票搜索表单 -->
      <div class="ticket-form">
        <!-- 舱位切换 -->
        <div class="trip-type">
          <span
            :class="{ active: cabinType === 'economy' }"
            @click="cabinType = 'economy'"
          >
            经济舱
          </span>
          <span
            :class="{ active: cabinType === 'business' }"
            @click="cabinType = 'business'"
          >
            头等舱
          </span>
        </div>

        <!-- 城市选择 -->
        <div class="city-select">
          <div class="city from" @click="showCityPicker('from')">
            <div class="name">{{ fromCity }}</div>
          </div>
          <div class="exchange">
            <van-icon
              class="exchange-icon"
              name="exchange"
              @click="exchangeCity"
            />
          </div>
          <div class="city to" @click="showCityPicker('to')">
            <div class="name">{{ toCity }}</div>
          </div>
        </div>

        <!-- 第一条分隔线 -->
        <div class="divider"></div>

        <!-- 日期选择 -->
        <div class="date-select" @click="openCalendar">
          <div class="date">
            <span class="day">{{ formatDate(selectedDate) }}</span>
            <span class="week">{{
              selectedDate
                ? "周" + "日一二三四五六"[new Date(selectedDate).getDay()] ||
                  "未知"
                : "明天"
            }}</span>
          </div>
        </div>

        <!-- 第二条分隔线 -->
        <div class="divider"></div>

        <!-- 搜索按钮 -->
        <div class="search-btn">
          <van-button
            block
            class="search-font"
            color="#ff9500"
            size="large"
            @click="handleSearch"
          >
            搜 索
          </van-button>
        </div>
      </div>

      <!-- 快捷功能区 -->
      <div class="quick-actions">
        <div class="action-item">
          <van-icon name="notes-o" />
          <span>机票订单</span>
        </div>
        <div class="action-item">
          <van-icon name="service-o" />
          <span>航班助手</span>
        </div>
        <div class="action-item">
          <van-icon name="friends-o" />
          <span>团体票</span>
        </div>
      </div>

      <!-- 服务保障 -->
      <div class="guarantee-wrapper">
        <service-guarantee use-card />
      </div>
    </div>

    <!-- 城市选择弹出层 -->
    <van-popup
      v-model="showCitySelect"
      :style="{ height: '80%' }"
      position="bottom"
      round
    >
      <div class="city-picker">
        <div class="picker-header">
          <div class="title">请选择城市</div>
          <van-icon name="cross" @click="showCitySelect = false" />
        </div>

        <!-- 搜索框 -->
        <div class="search-box">
          <van-search
            v-model="citySearchText"
            clearable
            placeholder="请输入城市名或三字码"
            shape="round"
            @clear="filteredCities = []"
          />
        </div>

        <!-- 搜索结果 -->
        <div v-if="filteredCities.length > 0" class="search-result">
          <div class="section">
            <div class="section-title">搜索结果</div>
            <div class="city-list">
              <div
                v-for="city in filteredCities"
                :key="city.code"
                class="city-item"
                @click="selectCity(city)"
              >
                <div class="city-name">{{ city.name }}</div>
                <div class="airport">{{ city.code }}</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 原有的城市列表，当没有搜索结果时显示 -->
        <div v-else class="city-content">
          <div class="section">
            <div class="section-title">最近出发</div>
            <div class="city-list">
              <div
                v-for="city in recentCities"
                :key="city.code"
                class="city-item"
                @click="selectCity(city)"
              >
                <div class="city-name">{{ city.name }}</div>
                <div class="airport">{{ city.code }}</div>
              </div>
            </div>
          </div>
          <div class="section">
            <div class="section-title">热门城市</div>
            <div class="city-list">
              <div
                v-for="city in hotCities"
                :key="city.code"
                class="city-item"
                @click="selectCity(city)"
              >
                <div class="city-name">{{ city.name }}</div>
                <div class="airport">{{ city.code }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </van-popup>

    <!-- 日期选择弹出层 -->
    <van-calendar
      v-model="showCalendar"
      :max-date="new Date(Date.now() + 15 * 24 * 60 * 60 * 1000)"
      :min-date="new Date()"
      :round="true"
      :show-confirm="true"
      color="#1890ff"
      title="选择日期"
      @confirm="onConfirmDate"
    />
  </div>
</template>

<script setup>
import { onMounted, ref, watch } from "vue";
import { useCalendar } from "@/hooks/useCalendar";
import ServiceGuarantee from "@/components/ServiceGuarantee.vue";
import cityAPI from "@/api/city";
import { message } from "@/utils/message";
import { useRouter } from "vue-router";
import { getToken } from "@/utils/auth";

const searchText = ref("");
const activeTab = ref(0);

// 城市选择相关
const fromCity = ref("北京");
const toCity = ref("上海");
const showCitySelect = ref(false);
const citySearchText = ref("");
const currentSelectType = ref(""); // 'from' 或 'to'
const filteredCities = ref([]);

// 城市数据
const cityList = ref({}); // 改回对象格式
const recentCities = ref([]);
const hotCities = ref([]);

// 获取明天的日期
const tomorrow = new Date(Date.now() + 24 * 60 * 60 * 1000);

// 添加舱位类型状态
const cabinType = ref("economy"); // 默认经济舱

// 添加 router 实例
const router = useRouter();

// 获取城市列表
const getCityList = async () => {
  try {
    // 获取所有城市列表
    const allCities = await cityAPI.getCityList();
    cityList.value = allCities.reduce((acc, city) => {
      acc[city.id] = city;
      return acc;
    }, {});

    // 获取热门城市列表
    const hotCitiesData = await cityAPI.getHotCities();
    hotCities.value = hotCitiesData;
  } catch (error) {
    console.error("获取城市数据失败:", error);
  }
};

// 获取最近访问城市列表
const getRecentCities = async () => {
  try {
    const recentCitiesData = await cityAPI.getRecentCities();
    recentCities.value = recentCitiesData;
  } catch (error) {
    console.error("获取最近访问城市失败:", error);
  }
};

// 修改搜索城市的方法
const searchCities = (searchText) => {
  if (!searchText) {
    filteredCities.value = [];
    return;
  }

  // 从对象中获取所有城市值并进行筛选
  filteredCities.value = Object.values(cityList.value).filter(
    (city) =>
      city.name.includes(searchText) ||
      city.code.toLowerCase().includes(searchText.toLowerCase())
  );
};

// 监听搜索文本变化
watch(citySearchText, (newValue) => {
  searchCities(newValue);
});

// 显示城市选择器
const showCityPicker = (type) => {
  currentSelectType.value = type;
  showCitySelect.value = true;
};

// 选择城市
const selectCity = (city) => {
  if (currentSelectType.value === "from") {
    fromCity.value = city.name;
  } else {
    toCity.value = city.name;
  }
  showCitySelect.value = false;
};

// 交换城市
const exchangeCity = () => {
  [fromCity.value, toCity.value] = [toCity.value, fromCity.value];
};

// 使用 useCalendar hook 时传入默认日期
const { showCalendar, selectedDate, formatDate, onConfirmDate, openCalendar } =
  useCalendar({
    defaultDate: tomorrow,
  });

// 在组件挂载时获取城市数据
onMounted(() => {
  getCityList();
  getRecentCities();
});

// 修改搜索按钮部分
const handleSearch = () => {
  router.push({
    path: "/flight-search",
    query: {
      from: fromCity.value,
      to: toCity.value,
      date: selectedDate.value,
      cabin: cabinType.value,
    },
  });
};

const handleUserClick = () => {
  if (getToken()) {
    router.push("/profile");
  } else {
    router.push("/login");
  }
};
</script>

<style lang="less" scoped>
.home {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 20px;

  .search-bar {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    display: flex;
    align-items: center;
    padding: 8px 16px;
    background: transparent;
    z-index: 100;

    .search-input {
      flex: 1;
      display: flex;
      align-items: center;
      background: rgba(255, 255, 255, 0.9);
      padding: 8px 12px;
      border-radius: 20px;
      margin-right: 12px;
      backdrop-filter: blur(10px);
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

      .search-icon {
        margin-right: 8px;
        color: #666;
        font-size: 16px;
      }

      .input-field {
        flex: 1;
        border: none;
        outline: none;
        background: transparent;
        font-size: 14px;
        color: #333;
        padding: 4px 0;
        width: 100%;

        &::placeholder {
          color: #999;
          font-size: 13px;
        }

        &:focus {
          outline: none;
          -webkit-tap-highlight-color: transparent;
        }
      }
    }

    .user-icon {
      font-size: 24px;
      color: #fff;
      opacity: 0.9;
    }
  }

  .main-content {
    position: relative;

    .bg-image {
      height: 200px;
      background-size: cover;
      background-image: url("@/assets/img/background.png");
    }

    .ticket-form {
      margin: -50px 16px 0;
      padding: 16px;
      background: #fff;
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

      .trip-type {
        display: flex;
        justify-content: center;
        margin-bottom: 20px;

        span {
          padding: 6px 24px;
          margin: 0 12px;
          border-radius: 16px;
          font-size: 14px;
          color: #666;
          cursor: pointer;
          transition: all 0.3s ease;

          &.active {
            background: #e6f7ff;
            color: #1890ff;
          }

          &:hover {
            opacity: 0.8;
          }

          &:active {
            transform: scale(0.98);
          }
        }
      }

      .city-select {
        display: flex;
        align-items: center;
        flex-wrap: nowrap;
        max-width: 100%;
        margin-bottom: 8px;
        padding: 0 20px;
        position: relative;

        .city {
          flex: 1;
          position: relative;

          .name {
            font-size: 22px;
            font-weight: 700;
            color: #333;
          }

          &.from {
            text-align: left;
            margin-right: 60px;
          }

          &.to {
            text-align: right;
            margin-left: 60px;
          }
        }

        .exchange {
          position: absolute;
          left: 50%;
          transform: translateX(-50%);
          width: 32px;
          height: 32px;
          display: flex;
          align-items: center;
          justify-content: center;
          background: #fff;
          border-radius: 50%;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
          z-index: 1;

          .exchange-icon {
            font-size: 20px;
            color: #1890ff;
          }
        }
      }

      .divider {
        height: 1px;
        background: #eee;
        margin: 0 20px;
      }

      .date-select {
        padding: 0 20px;
        margin: 30px 0 8px;
        cursor: pointer;

        .date {
          display: flex;
          align-items: flex-end;

          .day {
            font-size: 22px;
            font-weight: 700;
            color: #333;
            margin-right: 8px;
            line-height: 1;
          }

          .week {
            font-size: 14px;
            color: #666;
            padding-bottom: 0;
          }
        }

        &:active {
          opacity: 0.8;
        }
      }

      .search-btn {
        margin-top: 20px;
        padding: 0 16px;

        .search-font {
          font-size: 18px;
          font-weight: 700;
        }
      }
    }

    .quick-actions {
      display: flex;
      justify-content: space-between;
      padding: 20px 40px;
      margin: 16px;
      background: #fff;
      border-radius: 8px;
      width: calc(100% - 32px);

      .action-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        flex: 0 0 auto;

        .van-icon {
          font-size: 24px;
          color: #1890ff;
          margin-bottom: 8px;
        }

        span {
          font-size: 12px;
          color: #666;
        }
      }
    }

    .guarantee-wrapper {
      margin: 16px;

      :deep(.service-guarantee) {
        margin: 0;
        background: #fff;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
      }
    }
  }
}

.city-picker {
  height: 100%;
  display: flex;
  flex-direction: column;

  .picker-header {
    padding: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #f5f5f5;

    .title {
      font-size: 16px;
      font-weight: 500;
      color: #333;
    }

    .van-icon {
      font-size: 20px;
      color: #999;
    }
  }

  .city-tabs {
    display: flex;
    padding: 12px 16px;
    border-bottom: 1px solid #f5f5f5;

    .tab {
      padding: 6px 16px;
      font-size: 14px;
      color: #666;
      border-radius: 16px;
      margin-right: 12px;

      &.active {
        background: #1890ff;
        color: #fff;
      }
    }
  }

  .city-content {
    flex: 1;
    overflow-y: auto;

    .section {
      padding: 16px;

      .section-title {
        font-size: 14px;
        color: #999;
        margin-bottom: 12px;
      }

      .city-list {
        display: flex;
        flex-wrap: wrap;
        gap: 12px;

        .city-item {
          width: calc(33.33% - 8px);
          background: #f5f5f5;
          padding: 12px;
          border-radius: 8px;
          text-align: center;

          .city-name {
            font-size: 16px;
            color: #333;
          }

          .airport {
            font-size: 12px;
            color: #999;
            margin-top: 4px;
          }

          &:active {
            background: #e6f7ff;
          }
        }
      }
    }
  }

  .search-box {
    padding: 8px 16px;
    background: #fff;

    :deep(.van-search) {
      padding: 0;
      background: transparent;
    }

    :deep(.van-search__content) {
      background: #f5f5f5;
    }
  }

  .search-result {
    flex: 1;
    overflow-y: auto;
    background: #fff;

    .section {
      padding: 16px;

      .section-title {
        font-size: 14px;
        color: #999;
        margin-bottom: 12px;
      }

      .city-list {
        display: flex;
        flex-wrap: wrap;
        gap: 12px;
      }
    }
  }
}

// 修改城市选择区域的样式，添加点击效果
.city {
  &.from,
  &.to {
    cursor: pointer;
    padding: 8px;
    border-radius: 4px;
    transition: background-color 0.2s;

    &:active {
      background-color: #f5f5f5;
    }
  }
}

// 自定义日历样式
:deep(.van-calendar) {
  .van-calendar__header {
    box-shadow: none;
  }

  .van-calendar__selected-day {
    background: #1890ff;
  }
}
</style>
